from loguru import logger
import requests
from config import ENV

def login():
    data ={
        "params" :{"username": ENV.USERNAME,"password": ENV.PASSWORD},
        "method":"get",
        "url" :f"{ENV.HOST}adminapi/login"
    }
    r = requests.request(**data)
    return r.json()["data"]["token"]
token = login()


def request_hook(response,*args,**kwargs):
    logger.debug(f"响应结果：{response.text}")

class BaseRequest:                                                            # 基类，封装请求方法
    def __init__(self):                                                       #
        self._session = requests.Session()                                    # 实例化session对象
        self._session.headers.update({"token":token,"Content-type": "application/json"})                 # 更新请求头
        self._session.hooks["response"].append(request_hook)                  # 响应钩子函数
        self._requests = self._session                                        # 赋值给一个变量

    def _post(self, url, data, api_name):                                                 # 封装post请求方式
        base_url = ENV.HOST + url
        logger.debug(f"请求接口:{api_name},请求参数：{base_url}{data}")                                  # 打印请求参数
        return self._requests.post(url =base_url,json = data)                           # 返回post请求

    def _get(self, url, params , api_name):                                         # 封装get请求方式
        base_url = ENV.HOST + url
        logger.debug(f"请求接口:{api_name},请求参数：{base_url}{params}")                                # 打印请求参数
        return self._requests.get(url = base_url,params = params)                        # 返回get请求

    def _put(self, url, data, api_name):                                                  # 封装put请求方式
        base_url = ENV.HOST + url
        logger.debug(f"请求接口:{api_name},请求参数：{base_url}{data}")                                  # 打印请求参数
        return self._requests.put(url = base_url,json = data)                            # 返回put请求

    def _delete(self, url, params , api_name):                                       # 封装delete请求方式
        base_url = ENV.HOST + url
        logger.debug(f"请求接口:{api_name},请求参数：{base_url}{params}")                                 # 打印请求参数
        return self._requests.delete(url = base_url,params = params)                      # 返回delete请求


